'use strict';
// 部门
const Controller = require('egg').Controller;

class DepartController extends Controller {
    // 新增 编辑
    async edit() {
        const { ctx, app } = this
        const { id, parent, name } = ctx.request.body
        ctx.validate({
            name: {
                type: 'string',
                required: true,
                desc: '名称'
            },
        })
        let oneList, twoList
        if (id == 0) {//新建
            // 验证 名称是否已经存在
            oneList = await app.model.AdminDepart.findOne({
                where: {
                    name
                }
            })
            if (oneList) {
                ctx.throw(400, '名称已经存在')
            }
            twoList = await app.model.AdminDepart.create({
                parent, name
            })
        } else {//编辑
            oneList = await app.model.AdminDepart.findByPk(id)
            if (!oneList) {
                ctx.throw(400, '数据不存在')
            }
            twoList = await oneList.update({ parent, name })
        }
        ctx.apiSuccess(twoList)
    }
    // 部门列表
    async list() {
        const { ctx, app } = this
        let oneList = await ctx.page(app.model.AdminDepart)
        ctx.apiSuccess(oneList)
    }
    // 删除部门
    async del() {
        const { ctx, app } = this
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: 'id'
            }
        })
        let id = ctx.query.id

        let oneList = await app.model.AdminDepart.findByPk(id)
        if (!oneList) {
            ctx.throw(400, '数据不存在')
        }
        oneList = await oneList.destroy()
        if (!oneList) {
            ctx.throw(400, '操作失败')
        }
        ctx.apiSuccess('删除成功')
    }
}

module.exports = DepartController;
